package lowijs.XfireClient.util;

import java.security.*;

public class Util {
	public static String STORAGE_PATH = null;
	
	/**
	 * Hashes a plain text string with the SHA1 algorithm.
	 * @param plain a plain text string.
	 * @return the hashed string.
	 */
	public static String toSHA1(String plain) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			md.update(plain.getBytes());
			byte[] hash = md.digest();
			StringBuffer hexstring = new StringBuffer();
			for (int i = 0; i < hash.length; i++)
				hexstring.append(String.format("%02x", 0xFF & hash[i]));
			
			return hexstring.toString().toLowerCase();
		} catch (NoSuchAlgorithmException nsae) {
			return null;
		}
	}
	
	public static int findByteArray(byte[] source, byte[] key) {
		int possible = 0, currentKey = 0;
		boolean ontoSomething = false;
		
		for (int i = 0; i < source.length; i++) {
			if (source[i] == key[currentKey]) {
				if (!ontoSomething) {
					ontoSomething = true;
					possible = i;
				}

				if (++currentKey == key.length)
					return possible;
			} else if (ontoSomething) {
				ontoSomething = false;
				possible = 0;
				currentKey = 0;
			}
		}
		return -1;
	}
	
	public static int intFromBytes(byte[] data, int off, int len) {
		int result = 0;
		for (int i = 0; i < len; i++) {
			result |= (data[off + i] & 0xFF) << 8 * i;
		}
		return result;
	}
	
	public static long longFromBytes(byte[] data, int off, int len) {
		long result = 0;
		for (int i = 0; i < len; i++) {
			result |= (data[off + i] & 0xFF) << 8 * i;
		}
		return result;
	}
}
